package com.shujia.mvc.dao;

import com.shujia.mvc.bean.User;

import java.sql.*;

/**
 * 数据库访问层
 */
public class UserDao1 implements UserDaoInerace {

    static final String DRIVER = "com.mysql.jdbc.Driver";
    static final String URL = "jdbc:mysql://node1:3306/shujia";
    static final String USER = "root";
    static final String PASSWORD = "123456";

    static Connection conn;

    static {
        //加载驱动
        try {
            Class.forName(DRIVER);

            //获取连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据用户名查询用户
     */

    public User queryUserByUsername(String username) {

        User user = null;
        String sql = "select * from user where username=?";

        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, username);

            //执行查询
            ResultSet resultSet = preparedStatement.executeQuery();

            //如果用户名不存在返回null
            if (!resultSet.next()) {
                return null;
            }

            //去除字段
            String username1 = resultSet.getString("username");
            String password = resultSet.getString("password");


            user = new User(username1, password);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 插入数据
     */

    public void insert(User user) {

        String sql = "insert into user(username,password) values(?,?)";

        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);

            preparedStatement.setString(1, user.getUsernmae());
            preparedStatement.setString(2, user.getPassword());

            int i = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


}
